﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ArienToolkits.DBUntilities.SqlServer.Extension
{
    /// <summary>
    /// 表数据扩展类
    /// </summary>
    public static class TableDataExtension
    {
        /// <summary>
        /// 使用实体对象添加数据行
        /// </summary>
        /// <param name="helper">数据库操作辅助类</param>
        /// <param name="entity">实体对象</param>
        /// <param name="excludePrimaryKeyName">需要被剔除的主键列名称，多个主键使用逗号","分隔</param>
        /// <returns>添加是否成功</returns>
        public static bool AddNewRowByEntity(this SqlHelper helper, object entity, string excludePrimaryKeyName = null)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("实体对象不能为空");
            }

            Type t = entity.GetType();

            //获取表名
            string tableName = GetTableName(entity);

            //获取全部属性
            PropertyInfo[] properties = t.GetProperties();

            StringBuilder columnBuilder = new StringBuilder();
            StringBuilder valuesBuilder = new StringBuilder();

            List<SqlParameter> param = new List<SqlParameter>();

            string[] excludes = null;

            if (excludePrimaryKeyName != null)
            {
                excludes = excludePrimaryKeyName.ToLower().Split(',');
            }

            //循环所有属性
            foreach (PropertyInfo property in properties)
            {
                if (excludes != null && excludes.Contains(property.Name.ToLower()))
                {
                    //去除主键列
                    continue;
                }

                columnBuilder.AppendFormat("{0},", property.Name);
                valuesBuilder.AppendFormat("@{0},", property.Name);

                param.Add(new SqlParameter(string.Format("@{0}", property.Name), property.GetValue(entity)));
            }

            string sqlFmt = "INSERT INTO {0} ({1}) VALUES ({2})";
            string sql = string.Format(sqlFmt, tableName,
                columnBuilder.ToString().Substring(0, columnBuilder.Length - 1),
                valuesBuilder.ToString().Substring(0, valuesBuilder.Length - 1));

            int result = helper.ExecuteNonQuery(System.Data.CommandType.Text, sql, param.ToArray<SqlParameter>());

            return result > 1;
        }

        /// <summary>
        /// 获取表名(优先获取TABLENAME字段的值，否则返回类型名称)
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        internal static string GetTableName(object obj)
        {
            Type type = obj.GetType();

            FieldInfo field = type.GetField("TABLENAME");
            if (field == null)
            {
                return type.Name.Substring(type.Name.LastIndexOf(".") + 1);
            }
            else
            {
                return field.GetValue(obj).ToString();
            }
        }
    }
}
